-- 账户模块
-- Author: Colocasia
-- Date: 2018-05-22

local skynet = require 'skynet';
local crypt = require 'skynet.crypt';

local string = require 'us.string';
local os = os;

local class = require 'class';
local handler = require 'handler';
local md5 = require 'md5';
local log = require 'log';

---@class account : handler
local M = class('account', handler);

Account = M;
-- 其他模块加载
function M:ctor()
    self.super:ctor();
end
-- 其他模块加载

function M:test()
    local r = self:exc_db_cmd('account', 'find_account', 1);
    log.dump(self:auth("Aliner", "11111"), "auth");
end

-- 注册账户
function M:register(acc_name, acc_pwd)
    local result = self:exc_db_cmd('account', 'register_account', acc_name, acc_pwd);
    local code = result.code and tonumber(result.code);
    if code then
        if 23505 == code then
            return self:code('account_has_exist');
        end

        return self:code('unknow_error', string.format('db error code is %s', code));
    end
    return self:render({
        acc_id = result.account_insert,
    });
end

-- 账户认证
function M:auth(acc_name, acc_pwd)
    -- 查找账户
    local result = self:exc_db_cmd('account', 'find_account_by_name', acc_name);
    -- 账户不存在
    if not result then
        return self:code('account_not_exist');
    end

    local md5_pwd = md5.sumhexa(acc_pwd..acc_name);
    local real_pwd = tostring(result.pwd)
    if md5_pwd ~= real_pwd and acc_pwd ~= real_pwd then
        return self:code('account_pwd_error');
    end

    return self:render({
        token = self:gen_token(result.guid)
    }); 
end

-- 生成accout结果
local function gen_accout_result(result)
    return {
        id      = result.id,
        name    = result.name,
        guid    = result.guid,
        players = result.players,
        exp     = result.exp,
        -- gold    = aaccount.gold,
    };
end

-- 查找账户(id)
function M:find_account(acc_id)
    local result = self:exc_db_cmd('account', 'find_account', acc_id);
    -- 账户不存在
    if not result then return end
    return gen_accout_result(result);
end

-- 查找账户(guid)
function M:find_account_by_guid(acc_guid)
    local result = self:exc_db_cmd('account', 'find_account_by_guid', acc_guid);
    -- 账户不存在
    if not result then return end
    return gen_accout_result(result);
end

-- token生成
function M:gen_token(guid)
    if not guid then return end
    return crypt.base64encode(guid.."|"..os.time());
end

-- token解析
function M:parse_token(token)
    local token = crypt.base64decode(token)
    local info = string.split(token, "|");
    return info;
end

return M;
